<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="adduserdia">添加角色</el-button>
        </el-col>
      </el-row>
      <el-table class="eltable" :data="rolelist" stripe border>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row :class="['bdbottom', i1 === 0 ? 'bdtop':'', 'vcentr']" v-for="(item1,i1) in scope.row.children" :key="item1.id">
              <el-col :span="5">
                <el-tag closable @close="removerightbyid(scope.row.id, item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
<!--              二级权限-->
              <el-col :span="19">
                <el-row :class="'vcentr'" v-for="(item2) in item1.children" :key="item2.id">
                  <el-col :span="6">
                    <el-tag closable @close="removerightbyid(scope.row.id, item2.id)" type="success">{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag closable @close="removerightbyid(scope.row.id, item3.id)" type="warning" v-for="(item3) in item2.children" :key="item3.id">
                      {{item3.authName}}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button @click="edituser(scope.row.id)" size="mini" type="primary" icon="el-icon-edit">编辑</el-button>
            <el-button @click="removeuser(scope.row.id)" size="mini" type="danger" icon="el-icon-delete">删除</el-button>
            <el-button @click="showsetrights(scope.row)" size="mini" type="waring" icon="el-icon-setting">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-dialog @close="addclose"
      title="添加角色"
      :visible.sync="adduser"
      width="50%">
      <el-form ref="addformref" :model="addform" label-width="80px" :rules="addformrules">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addform.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addform.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="adduser = false">取 消</el-button>
    <el-button type="primary" @click="adduserconfirm">确 定</el-button>
  </span>
    </el-dialog>
    <el-dialog @close="editclose"
      title="编辑角色"
      :visible.sync="editdia"
      width="50%">
      <el-form ref="editdataref" :model="editdata" label-width="70px">
        <el-form-item label="角色名称">
          <el-input v-model="editdata.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="editdata.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editdia = false">取 消</el-button>
        <el-button type="primary" @click="editshow">确 定</el-button>
      </span>
    </el-dialog>
<!--    分配权限对话框-->
    <el-dialog
      title="分配权限"
      :visible.sync="setrightsdialogVisible"
      width="50%" @close="setrightclose">
      <el-tree ref="treeRef" :data="rightlist" :props="treeProps" show-checkbox node-key="id" :default-checked-keys="defkeys"></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setrightsdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotrights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Roles',
  data () {
    return {
      rolelist: [],
      adduser: false,
      addform: {
        roleName: '',
        roleDesc: ''
      },
      addformrules: {
        roleName: [{ required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 3, max: 10, message: '用户名长度在3-10个字', trigger: 'blur' }],
        roleDesc: [{ required: true, message: '请输入角色描述', trigger: 'blur' }]
      },
      editdia: false,
      editdata: {},
      setrightsdialogVisible: false,
      rightlist: [],
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      defkeys: [],
      roleId: ''
    }
  },
  created() {
    this.getroleslist()
  },
  methods: {
    async getroleslist () {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取失败')
      }
      this.rolelist = res.data
    },
    adduserdia () {
      this.adduser = true
    },
    addclose () {
      this.$refs.addformref.resetFields()
    },
    // 提交前的预验证
    adduserconfirm () {
      this.$refs.addformref.validate(async valid => {
        if (!valid) {
          return
        }
        const { data: res } = await this.$http.post('roles', this.addform)
        if (res.meta.status !== 201) {
          this.$message.error('角色创建失败')
        }
        this.$message.success('角色创建成功')
        this.adduser = false
        this.getroleslist()
      })
    },
    async edituser (id) {
      const { data: res } = await this.$http.get('roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('查询失败')
      }
      this.editdata = res.data
      this.editdia = true
    },
    editclose () {
      this.$refs.editdataref.resetFields()
    },
    async editshow () {
      const { data: res } = await this.$http.put('roles/' + this.editdata.roleId, { roleName: this.editdata.roleName, roleDesc: this.editdata.roleDesc })
      if (res.meta.status !== 200) {
        return this.$message.error('失败')
      }
      this.editdia = false
      this.getroleslist()
      this.$message.success('更新用户成功')
    },
    async removeuser (id) {
      const confirmres = await this.$confirm('确认删除吗', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => {
        return err
      })
      if (confirmres !== 'confirm') {
        return this.$message.info('已经取消')
      }
      const { data: res } = await this.$http.delete('roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('失败')
      }
      this.$message.success('成功')
      this.getroleslist()
    },
    async removerightbyid (role, rightid) {
      const confirmres = await this.$confirm('此操作将永久删除该权限, 是否继续?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => {
        return err
      })
      if (confirmres !== 'confirm') {
        return this.$message.info('取消了删除')
      }
      const { data: res } = await this.$http.delete(`roles/${role}/rights/${rightid}`)
      if (res.meta.status !== 200) {
        console.log(res)
        return this.$message.error('删除失败')
      }
      this.getroleslist()
      // role.children = res.data
      this.$message.success('删除成功')
    },
    async showsetrights (role) {
      this.roleId = role.id
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限列表失败')
      }
      this.rightlist = res.data
      console.log(this.rightlist)
      this.getleafkeys(role, this.defkeys)
      this.setrightsdialogVisible = true
    },
    getleafkeys (node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getleafkeys(item, arr)
      })
    },
    setrightclose () {
      this.defkeys = []
    },
    async allotrights () {
      const keys = [
        ...this.$refs.treeRef
          .getCheckedKeys(),
        ...this.$refs.treeRef
          .getHalfCheckedKeys()
      ]
      const idStr = keys.join(',')
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idStr })
      if (res.meta.status !== 200) {
        return this.$message.error('分配时报')
      }
      this.$message.success('分配权限成功')
      this.getroleslist()
      this.setrightsdialogVisible = false
    }
  }
}
</script>

<style scoped>
  .eltable{
    margin-top: 20px;
  }
  .el-tag{
    margin: 7px;
  }
  .bdtop{
    border-top: 1px solid #b2b2b2;
  }
  .bdbottom{
    border-bottom: 1px solid #b2b2b2;
  }
  .vcentr{
    display: flex;
    align-items: center;
  }
</style>
